<template>
  <div>
    <div>
      <div class="title">Head 保养可视化监控
        <!-- <div class="title">保养预警 - <span style="font-size:medium;">Head维护信息（按下次保养时间由近到远排序）</span> -->
        <!-- （此界面可直接扫码HeadSN进入保养维护登记） -->
      </div>
    </div>
    <div class="line"></div>
    <div class="button">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>

    </div>
    <!-- <div class="tishi" v-if="showMessage">
      提示：
      <span class="message">无head信息！</span>
    </div>-->
    <el-table :data="tableData" style="width: 100%" :header-cell-style="headerStyleEvent"
      :cell-class-name="tableCellClassName" @cell-click="cellClick" border>
      <!-- <el-table-column prop="id" label="id" width="100" align="center"></el-table-column> -->
      <el-table-column prop="headSN" label="HeadSN" width="120" align="center">
        <template slot-scope="{row}">
          <el-link type="primary" size="small" @click="toMaintain(row)" title="保养记录">{{ row.headSN }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="headType" label="HeadType" width="120" align="center"></el-table-column>
      <el-table-column prop="placeStatus" label="位置状态" width="100" align="center"></el-table-column>
      <el-table-column prop label="位置" align="center">
        <template slot-scope="{row}">{{ placeInfo(row) }}</template>
      </el-table-column>
      <!-- <el-table-column prop="nextWeekMainteDate" label="下一次周保养" width align="center"></el-table-column> -->
      <el-table-column prop="nextMonthMainteDate" label="下一次月保养" width align="center"></el-table-column>
      <el-table-column prop="nextQuarterMainteDate" label="下一次季保养" width align="center"></el-table-column>
      <el-table-column prop="nextYearMainteDate" label="下一次年保养" width align="center"></el-table-column>
      <el-table-column prop="headTotalCnt" label="使用总次数" align="center"></el-table-column>
      <el-table-column prop="totalHeadCnt_forScrap" label="报废的总次数" align="center"></el-table-column>
      <el-table-column prop="isNeedScraped" label="是否应该报废" width="70px" align="center">
          <template slot-scope="{row}">
              <p v-if="row.isNeedScraped" style="color:red;">Yes</p>
              <p v-else>No</p>
          </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleScraped(row)">报废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增和编辑 -->
    <addDialog v-if="addDialogVisible" v-model="addDialogVisible" :dialog-title="dialogTitle" @close="getTableData"
      @refresh="addDialogRefresh" :item-info="headDialogProps"></addDialog>
    <Pagination :total="total" :page.sync="page" :limit.sync="limit" @pagination="handlePagination"></Pagination>
    
        <el-dialog
            title="确认报废吗？"
            :visible="scrapedDialogVisible"
            width="30%">
            <span>{{scrapedDataInfo.warn}}</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="scrapedDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleScrapedMaterial">确 定</el-button>
            </span>
        </el-dialog>
  
  </div>
</template>
<script>
import { getHeaderInfo, getSnExists,fetchScrapedHeadMainte } from '@/network/headMaintain'
import Pagination from '@/components/Pagination.vue'
import addDialog from './components/addDialog.vue'
export default {
  name: 'headMaintain',
  props: {},
  components: { Pagination, addDialog },
  data() {
    return {
      tableData: [],
      page: 1,
      limit: 20,
      total: 0,
      addDialogVisible: false,
      dialogTitle: '新增',
      headDialogProps: {
        headSN: '',
        headType: '',
        placeInStoreStatus: 0,
        placeId: '',
        nextWeekMainteDate: '',
        nextMonthMainteDate: '',
        nextQuarterMainteDate: '',
        nextYearMainteDate: ''
      },
      showMessage: false,
      scrapedDataInfo:{
            warn:''
        },
      scrapedDialogVisible:false,
    }
  },
  mounted() {
    this.getTableData()
    // 监听按键
    var code = ''
    var lastTime, nextTime // 上次时间、最新时间
    var lastCode, nextCode // 上次按键、最新按键
    document.onkeypress = (e) => {
      // 获取按键
      if (window.event) { // IE
        nextCode = e.keyCode
      } else if (e.which) { // Netscape/Firefox/Opera
        nextCode = e.which
      }
      // 如果触发了回车事件(扫码结束时间)
      if (nextCode === 13) {
        if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
        this.codeFind(code) // 获取到扫码枪输入的内容，做别的操作
        code = ''
        lastCode = ''
        lastTime = ''
        return
      }
      nextTime = new Date().getTime() // 记录最新时间
      if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
        code += e.key // 执行叠加操作
      }
      // 如果有上次时间及上次按键
      if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
        code = e.key
      } else if (lastCode && lastTime) {
        code += e.key
      }
      lastCode = nextCode
      lastTime = nextTime
    }
  },
  methods: {
    codeFind(code) {
      console.log(code + '扫描成功');
      let codes = code + ""
      this.headDialogProps.headSN = encodeURIComponent(codes)
      this.isSnExisit()
    },
    addDialogRefresh(isAdd, data) {
      if (isAdd) {
        this.tableData.unshift(data)
      }
      else {

      }
    },
    async getTableData() {
      try {
        const res = await getHeaderInfo({ page: this.page, limit: this.limit })
        this.tableData = res.data
        this.total = res.count
      } catch (error) {
        console.log(error);
      }

      // 定时
      setTimeout(() => {
        this.getTableData();
      }, 60 * 60 * 1000);
    },
    async isSnExisit() {
      try {
        const res = await getSnExists({ headSN: this.headDialogProps.headSN })
        console.log(res);
        if (res.data) {
          // this.showMessage = false
          this.$router.push({
            path: `/spa/headMaintainRecordScan`,
            // query: {
            //   headSN: this.headDialogProps.headSN,
            // }
          })
        } else {
          // this.showMessage = true
          this.$message({
            showClose: true,
            message: '无head信息',
            type: 'error'
          });
        }
      } catch (error) {
        console.log(error);
      }
    },

    handlePagination(val) {
      this.page = val.page;
      this.limit = val.limit;
      this.getTableData()
    },
    //编辑
    handleEdit(row) {
      this.dialogTitle = '编辑'
      this.addDialogVisible = true
      this.headDialogProps = {
        id: row.id,
        headSN: row.headSN,
        headType: row.headType,
        placeId: row.placeInStoreInfo?.placeId,
        nextWeekMainteDate: row.nextWeekMainteDate,
        nextMonthMainteDate: row.nextMonthMainteDate,
        nextQuarterMainteDate: row.nextQuarterMainteDate,
        nextYearMainteDate: row.nextYearMainteDate,
        placeInStoreStatus: row.placeStatus,
        totalHeadCnt_forScrap:row.totalHeadCnt_forScrap
      }
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增'
      this.addDialogVisible = true
      const currDate = new Date();
      //currDate.getFullYear(); currDate.getMonth() + 1;currDate.getDate();

      this.headDialogProps = {
        headSN: '',
        headType: '',
        placeInStoreStatus: 0,
        placeId: '',
        nextWeekMainteDate: `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()}`,
        nextMonthMainteDate: `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()}`,
        nextQuarterMainteDate: `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()}`,
        nextYearMainteDate: `${currDate.getFullYear()}-${currDate.getMonth() + 1}-${currDate.getDate()}`,
        totalHeadCnt_forScrap:0,
      }
    },
    async handleScraped(row){            
        if(!row.isNeedScraped){
                this.scrapedDataInfo.warn='似乎不应该报废，确认仍旧报废吗？';
        }
        else{
            this.scrapedDataInfo.warn='确定报废吗？';
        }
        this.scrapedDataInfo.id = row.id;
        this.scrapedDialogVisible = true;
    },
    async handleScrapedMaterial(){
        try {
            const res = await fetchScrapedHeadMainte({id:this.scrapedDataInfo.id,
                isScraped:true
            })
            if (res.status == 200) {
                this.$message({
                    message: '报废成功',
                    type: 'success'
                });
                this.getTableData()
                this.scrapedDialogVisible = false;
            }
        } catch (error) {
            console.log(error);
        }
    },
    toMaintain(row) {
      this.$router.push({
        path: `/spa/headMaintainRecordScan`,
        query: {
          // id: row.id,
          headSN: row.headSN
        }
      })
    },
    headerStyleEvent({ row, columnIndex }) {
      //   if (columnIndex == 5 || columnIndex == 6) {
      //     //表头隐藏
      //     return { display: "none" };
      //   }
      //   row[4].colSpan = 3;
      //   row[5].colSpan = 0;
      //   row[6].colSpan = 0;
      return { background: '#eef1f6', color: '#606266' }
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {//注意这里是解构
      //利用单元格的 className 的回调方法，给行列索引赋值
      row.index = rowIndex;
      column.index = columnIndex;
    },
    cellClick(row, column, cell, event) {
      console.log(row.index);
      console.log(column.index);
    },
    placeInfo(row) {
      if (row.placeStatus === 'onLine') {
        return `${row.placeOnlineInfo?.lineName} / ${row.placeOnlineInfo?.machineName} / ${row.placeOnlineInfo?.modulePosition}`;
      }
      else if (row.placeStatus === 'inStore') {
        return `${row.placeInStoreInfo?.placeHouse || ''} / ${row.placeInStoreInfo?.placeSpecificNo || ''}`;
      }
      else if (row.placeStatus === 'outStore') {
        return row.placeOutStoreInfo?.msg;
      }
    }
  }
}
</script>
<style scoped>
.button {
  margin: 10px;
}

.message {
  color: red;
}

.tishi {
  margin: 10px;
}

.title {
  font-size: 24px;
  margin-left: 100px;
  margin-bottom: 8px;
  /* font-weight: bold; */
  /* font-family: 思源宋体 SemiBold; */
}

.line {
  background: linear-gradient(to left, #ffffff, #637ca0, #ffffff);
  height: 3px;
  margin-bottom: 8px;
}
</style>